from fastapi import APIRouter, Depends, Body

from odoo.api import Environment
from odoo.addons.fastapi.dependencies import odoo_env
from odoo.addons.fastapi_odoo_bridge.core.exception import BusinessException, CustomResponse
from odoo.addons.fastapi_odoo_bridge.core.response import custom_response
from ..basemodels.fir_level import TranslationLine, TranslationTable, TranslationProgram, TranslationClient
from odoo.addons.rp_international_management.functions.rp_translation_table_fc import RPTranslationTableFC

from .common_rt import get_program_and_client

router = APIRouter(prefix='/html', tags=['html 调用方式'])


@router.post(
    path='/batch_upload',
    summary='批量上传多语言记录',
    description='批量上传，如果没有则创建，如果有则更新。需要注意的是，要按照三级索引的规则进行操作',
    response_model=CustomResponse[dict]
)
@custom_response
async def batch_upload(table: TranslationTable = Body(..., description='项目'), env: Environment = Depends(odoo_env)):
    # 获取终端，项目
    program, client = get_program_and_client(env, table.program, table.client)
    # 遍历line，创建或更新翻译对照表
    for line in table.line:
        RPTranslationTableFC(env).update_table(program=program, client=client, index=line.index, chinese=line.chinese, english=line.english,
                                               spanish=line.spanish, catalan=line.catalan)
    return {'result': 'OK'}


@router.post('/batch_download',
             response_model=CustomResponse[TranslationTable],
             summary='批量获取多语言记录',
             description='批量获取多语言记录')
@custom_response
async def batch_download(table: TranslationTable = Body(..., description='项目'),
                         env: Environment = Depends(odoo_env)):
    program, client = get_program_and_client(env, table.program, table.client)

    table_line = env['rp.translation.table'].search([('program_id', '=', program.id), ('client_id', '=', client.id)])

    translation_table = TranslationTable(program=TranslationProgram(__from_odoo=program, __env=env),
                                         client=TranslationClient(__from_odoo=client, __env=env),
                                         line=[TranslationLine(__from_odoo=line, __env=env) for line in table_line])

    return translation_table
